package api

import (
	"django_blog_gin/internal/dto"
	"django_blog_gin/internal/model"
	"django_blog_gin/internal/svc"
	"django_blog_gin/internal/utils"
	"fmt"

	"github.com/gin-gonic/gin"
)

type loginController struct {
	svcCtx *svc.ServiceContext
}

func NewLoginController(scvCtx *svc.ServiceContext) gin.HandlerFunc {
	c := &loginController{
		scvCtx,
	}
	return c.login
}

func (c *loginController) login(ctx *gin.Context) {
	var loginReq dto.UserLoginReq
	if !utils.ValidateJsonBody(ctx, &loginReq) {
		return
	}

	userModel := model.AccountsBlogUser{}
	err := c.svcCtx.MysqlDb.Get(&userModel, "select id,username,email,password from accounts_bloguser where username=?", loginReq.Username)
	if err != nil {
		fmt.Println(err.Error())
		utils.ResponseError(ctx, 1002, "用户名不存在的用户")
		return
	}
	_, err = utils.VerifyPassword(userModel.Password, loginReq.Password)
	if err != nil {
		utils.ResponseError(ctx, 1003, "密码错误")
		return
	}
	data := gin.H{
		"account": utils.GenerateAccountToken(loginReq.Username, userModel.Id),
		"refresh": utils.GenerateRefreshToken(loginReq.Username, userModel.Id),
	}
	utils.ResponseSuccess(ctx, data, "登录成功")
}
